<template>
  <div style="background-color: #F5F5F5; height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; box-sizing: border-box;">

    <!-- 容器：包裹左右两部分，居中并紧凑布局 -->
    <div style="display: flex; width: 100%; max-width: 1200px; height: 90vh; gap: 16px;">

      <!-- 左侧：知识库分类导航 -->
      <div class="knowledge-sidebar" style="
        width: 260px;
        background-color: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        padding: 20px;
        display: flex;
        flex-direction: column;
        gap: 16px;
        height: 100%;
        overflow-y: auto;
      ">
        <div style="text-align: center; padding: 10px 0;">
          <h2 style="font-size: 20px; color: #c62828; margin: 0;">知识导航</h2>
          <p style="font-size: 13px; color: #666; margin-top: 6px;">点击快速提问</p>
        </div>

        <div v-for="cat in categories" :key="cat.key" class="category-item">
          <div
              @click="loadSampleQuestion(cat.sample)"
              @mouseenter="handleMouseEnter"
              @mouseleave="handleMouseLeave"
              style="
                padding: 14px;
                border-radius: 12px;
                background-color: #f9f9f9;
                cursor: pointer;
                transition: all 0.3s ease;
                border: 1px solid #ebeef5;
                display: flex;
                align-items: center;
                gap: 10px;
                font-size: 14px;
              "
          >
            <span style="font-size: 22px;">{{ cat.icon }}</span>
            <div style="flex: 1;">
              <div style="font-weight: 600; color: #333;">{{ cat.title }}</div>
              <div style="font-size: 12px; color: #666; margin-top: 2px;">{{ cat.desc }}</div>
            </div>
          </div>
        </div>

        <!-- 底部留白撑起 -->
        <div style="flex: 1;"></div>
      </div>

      <!-- 右侧：主问答卡片 -->
      <el-card
          shadow="never"
          style="
            flex: 1;
            max-width: 800px;
            height: 100%;
            border-radius: 20px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            background-color: white;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
          "
      >
        <!-- 标题区 -->
        <div class="header-section" style="padding: 20px; text-align: center; border-bottom: 1px solid #eee;">
          <h1 class="title">壮锦纹样文化问答</h1>
          <p class="subtitle" style="margin: 6px 0 0; color: #666; font-size: 14px;">
            探索壮锦纹样的文化密码：寓意解读 · 历史溯源 · 工艺传承
          </p>
        </div>

        <!-- 主内容区：AI 回答 + 提问 -->
        <div style="flex: 1; display: flex; flex-direction: column; overflow: hidden;">

          <!-- AI 回答区域（固定高度，可滚动） -->
          <div
              ref="answerContainerRef"
              class="answer-container"
              style="
                height: 280px;
                padding: 20px;
                overflow-y: auto;
                border-bottom: 1px solid #eee;
                background-color: #f9f9f9;
                transition: opacity 0.2s;
              "
              :style="{ opacity: currentAnswer || isLoading ? 1 : 0.6 }"
          >
            <el-card v-if="currentAnswer || isLoading" shadow="light" style="border-left: 4px solid #409EFF; border-radius: 12px; background-color: transparent; box-shadow: none;">
              <template #header>
                <div style="display: flex; align-items: center; gap: 6px;">
                  <el-icon style="color: #409EFF;"><ChatLineRound /></el-icon>
                  <span style="font-weight: 600; color: #333; font-size: 15px;">AI 助手的回答</span>
                </div>
              </template>
              <div class="answer-content" style="line-height: 1.6; color: #333; font-size: 14px;">
                <p v-if="currentAnswer" v-html="formattedAnswer"></p>
                <el-skeleton v-else :rows="3" animated style="margin-top: 0;" />
                <div v-if="isLoading" class="typing-indicator" style="margin-top: 10px; display: flex; align-items: center; color: #909399; font-size: 13px;">
                  <el-icon><Loading class="loading-icon"/></el-icon> 正在生成回答...
                </div>
              </div>
            </el-card>

            <!-- 默认提示 -->
            <div v-if="!currentAnswer && !isLoading" style="color: #999; font-size: 14px; text-align: center; margin-top: 30px;">
              AI 助手将在此展示回答
            </div>
          </div>

          <!-- 提问区 -->
          <div style="padding: 20px; display: flex; gap: 10px; flex-direction: column;">
            <div style="display: flex; gap: 10px; width: 100%;">
              <el-input
                  v-model="userQuestion"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入您关于壮锦纹样的问题..."
                  :disabled="isLoading"
                  @keydown.enter.exact.prevent="askQuestion"
                  clearable
                  style="flex: 1;"
              />
              <el-button
                  type="primary"
                  @click="askQuestion"
                  :disabled="!userQuestion.trim() || isLoading"
                  style="width: 90px; flex-shrink: 0; height: auto; font-size: 14px;"
              >
                {{ isLoading ? '回答中...' : '提问' }}
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUpdated, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, ChatLineRound } from '@element-plus/icons-vue'

// 响应式数据
const userQuestion = ref('')
const currentAnswer = ref('')
const isLoading = ref(false)
const answerContainerRef = ref<HTMLElement | null>(null)

// 分类引导卡片
const categories = [
  {
    key: 'meaning',
    icon: '🎨',
    title: '纹样寓意解读',
    desc: '了解蟒龙纹、万寿纹等象征意义',
    sample: '蟒龙纹有什么寓意？'
  },
  {
    key: 'history',
    icon: '📜',
    title: '历史典故溯源',
    desc: '探索壮锦起源与发展历程',
    sample: '壮锦最早出现在哪个朝代？'
  },
  {
    key: 'craft',
    icon: '🧵',
    title: '工艺技巧讲解',
    desc: '学习传统织造与纹样组合方法',
    sample: '回纹是怎么织出来的？'
  }
]

// 加载示例问题
const loadSampleQuestion = (question: string) => {
  userQuestion.value = question
}

// 处理换行符
const formattedAnswer = computed(() => {
  return currentAnswer.value.replace(/\n/g, '<br>')
})

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (answerContainerRef.value) {
      answerContainerRef.value.scrollTop = answerContainerRef.value.scrollHeight
    }
  })
}

// 鼠标悬停样式
const handleMouseEnter = (e: MouseEvent) => {
  const target = e.currentTarget as HTMLElement
  target.style.backgroundColor = '#eef7ff'
  target.style.transform = 'translateY(-2px)'
}

// 鼠标离开样式
const handleMouseLeave = (e: MouseEvent) => {
  const target = e.currentTarget as HTMLElement
  target.style.backgroundColor = '#f9f9f9'
  target.style.transform = 'translateY(0)'
}

// 提问逻辑（对接后端流式接口）
const askQuestion = async () => {
  const q = userQuestion.value.trim()
  if (!q) return

  currentAnswer.value = ''
  isLoading.value = true

  try {
    const response = await fetch('http://localhost:8080/api/largeModel/ask', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ question: q })
    })

    if (!response.ok || !response.body) {
      throw new Error('服务异常，请稍后重试')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })

      // 按 \n\n 分割 SSE 事件
      let lines = buffer.split('\n\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.substring(6).trim()
          if (data === '[DONE]' || data === '') continue
          currentAnswer.value += data
          scrollToBottom() // 新增内容后自动滚动
        }
      }
    }
  } catch (error) {
    console.error('流式请求出错:', error)
    ElMessage.error('回答生成失败，请稍后重试')
    currentAnswer.value = '抱歉，当前无法生成回答，请稍后再试。'
    scrollToBottom()
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 自动滚动（当回答更新时）
onUpdated(() => {
  if (currentAnswer.value || isLoading.value) {
    scrollToBottom()
  }
})
</script>

<style scoped>
.title {
  font-size: 22px;
  font-weight: 700;
  color: #c62828;
  margin: 0;
}

.subtitle {
  font-size: 14px;
  color: #555;
}

.loading-icon {
  animation: rotating 1.5s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>